package controller;

import util.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 高杰  gao4433@qq.com
 * @Description
 * @date 2021/12/10 16:42
 * @since 1.8
 */

public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取会话作用域对象
        HttpSession session = request.getSession();

        // 使用 Request 的 getParameter 方法获取查询字符串中键为 u 的值
        String username = request.getParameter("u");
        // 使用 Request 的 getParameter 方法获取查询字符串中键为 p 的值
        String password = request.getParameter("p");

        String code = request.getParameter("c");

        Object ccc = session.getAttribute("ccc");
        boolean codeIsTrue = code != null && code.equals(ccc);

        if (!codeIsTrue) {
            //输入的验证码和存储在session中的值不一样
            response.sendRedirect("/code_error.jsp");
//            response.sendRedirect("/login.jsp");
        } else {
            // 查询数据库，验证账号密码的存在性
            String sql = "SELECT id FROM `user` WHERE `username` = ? AND `password` = MD5(?)";
            Integer id = JdbcUtils.select(sql, Integer.class, username, password);
            if (id != null) {
                session.setAttribute("UID", id);
                //重定向到首页
                response.sendRedirect("/index.jsp");
            } else {
                //重定向到登录页
                response.sendRedirect("/login_error.jsp");
//                response.sendRedirect("/login.jsp");
            }

        }

    }

}

